package com.changanw.code19;

import java.util.ArrayList;
import java.util.List;

/**
 * @author changanw
 * @version ncc1.0
 * @description TODO
 * @date 2023/7/5 20:53
 */
public class Code19 {
  public ListNode removeNthFromEnd(ListNode head, int n) {
    List<Integer> list = new ArrayList<>();
    //遍历链表，将数据放入list，便于后续移除
    while (head != null){
      int a = head.val;
      list.add(a);
      head = head.next;
    }
    //判断大小移除的元素的索引刚好是，size-n
    int size = list.size();
    if (size >= n){
      list.remove(size-n);
    }
    //然后基于移除元素后的list重新创建链表
    ListNode res = new ListNode(0);
    ListNode cur = res;
    for (Integer integer : list) {
      cur.next = new ListNode(integer);
      cur = cur.next;
    }

    return res.next;

  }

  public static void main(String[] args) {
    Code19 code19 = new Code19();
    ListNode head = new ListNode(1);
    head.next = new ListNode(2);
    code19.removeNthFromEnd(head,1);
  }
  static class ListNode{
    int val;
    ListNode next;
    ListNode() {

    }
    ListNode(int val) {
      this.val = val;
    }
    ListNode(int val, ListNode next) {
      this.val = val; this.next = next;
    }
  }
}
